﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BattleEntityFactory : Singleton<BattleEntityFactory>
{
    private int m_iInitId = 5000;

    private List<int> m_lisRemoveId = new List<int>();
    //private List<BattleEntity> m_lisAllBtEntity = new List<BattleEntity>();
    //key,lisIndex
    private Dictionary<int, BattleEntity> m_dicAllBtEntity = new Dictionary<int, BattleEntity>();

    public T CreateBtEntity<T>() where T : BattleEntity
    {
        T player = System.Activator.CreateInstance<T>();
        player.Init(m_iInitId);
        //m_lisAllBtEntity.Add(player);
        m_dicAllBtEntity.Add(m_iInitId, player);
        m_iInitId++;
        return player;
    }

    public BattleEntity GetBtEntity(int id)
    {
        if (m_dicAllBtEntity.ContainsKey(id))
        {
            return m_dicAllBtEntity[id];
        }
        Debug.Log(id.ToString() + " 的实体没有找到");
        return null;
    }

    public bool DestroyEntity(int id)
    {
        if (m_dicAllBtEntity.ContainsKey(id))
        {
            m_lisRemoveId.Add(id);
            return true;
        }

        return false;
    }

    public void OnUpdate(float deltaTime)
    {
        foreach (var entity in m_dicAllBtEntity.Values)
        {
            entity.OnUpdate(deltaTime);
        }
        if(m_lisRemoveId.Count > 0)
        {
            for (int i = 0; i < m_lisRemoveId.Count; i++)
            {
                m_dicAllBtEntity[m_lisRemoveId[i]].OnDestroy();
                m_dicAllBtEntity.Remove(m_lisRemoveId[i]);
            }
            m_lisRemoveId.Clear();
        }
    }
}
